package view.backing;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import oracle.adf.view.rich.component.rich.output.RichOutputText;

import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;

import view.utils.JSFUtils;


public class TestBean
{
  public TestBean()
  {
    super();
  }


  public Object invokeMethodExpression(String expr, Class returnType,
                                       Class[] argTypes, Object[] args)
  {
    FacesContext fc = FacesContext.getCurrentInstance();
    ELContext elctx = fc.getELContext();
    ExpressionFactory elFactory =
      fc.getApplication().getExpressionFactory();
    MethodExpression methodExpr =
      elFactory.createMethodExpression(elctx, expr, returnType, argTypes);
    return methodExpr.invoke(elctx, args);
  }

  public String createNewRow()
  {

    return null;
  }

  private void displayStatusPopup(String message, UIComponent componentId)
  {
    FacesContext fctx = FacesContext.getCurrentInstance();
    StringBuilder script = new StringBuilder();
    String commandID = null;
    ((RichOutputText) JSFUtils.findComponent("deliveryMessage")).setValue(message);
    String popupId =
      JSFUtils.findComponent("deliveryPopup").getClientId(fctx);
    //    if (JSFUtils.findComponent(componentId) != null)
    //    {
    commandID = componentId.getClientId(fctx);
    //    }

    script.append("var popup = AdfPage.PAGE.findComponent(\"").append(popupId).append("\");");
    if (commandID != null)
    {
      script.append("var hints = {align:\"end_after\", alignId:\"").append(commandID).append("\"};");
    }
    script = script.append("popup.show(hints);");

    Service.getRenderKitService(fctx,
                                ExtendedRenderKitService.class).addScript(fctx,
                                                                          script.toString());
  }

  public void onCreateNewRow(ActionEvent actionEvent)
  {
    String expr = "#{bindings.CreateInsert.execute}";
    //    invokeMethodExpression(expr, null, new Class[]
    //        { }, null);
    displayStatusPopup("Ready to create new record. Scroll up to see the entry fields",
                       actionEvent.getComponent());
  }
}
